import router from '@/router'
import store from '@/store'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  if (store.getters.token) {
    if (to.path === 'login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const routers = await store.dispatch('permisson/filters', roles.menus)
        router.addRoutes([
          ...routers,
          { path: '*', redirect: '/404', hidden: true }
        ])
        // Vue Router 4的新写法,只能一个一个添加
        /* routers.forEach(element => {
          router.addRoute(element)
        }) */

        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})
router.afterEach(() => {})
